package top.meeting.room.common.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.xiaoleilu.hutool.io.FileUtil;
import top.jfinal.jwtTokenPlugin.interceptor.AuthInterceptor;
import top.jfinal.jwtTokenPlugin.interceptor.JwtTokenInterceptor;
import top.meeting.room.common.base.BaseRender;
import top.meeting.room.common.model.Files;

import java.io.File;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/22
 * FOR : 基本Controller
 */
@Clear({JwtTokenInterceptor.class, AuthInterceptor.class})
public class IndexController extends BaseRender {
    /**
     * 上传文件
     */
    @Before({Tx.class})
    public void upload() {
        List<UploadFile> fileList = getFiles();
        List<Files> filesList = new LinkedList<Files>();
        String basePackage = getPara("basePackage");
        String description = getPara("description");
        String basePath = PathKit.getRootClassPath();
        String base = "";
        if (StrKit.isBlank(basePackage))
            base = "/SYSTEM";
        else
            base = basePackage;
        Date date = new Date();
        for (UploadFile uploadFile : fileList) {
            File src = uploadFile.getFile();
            String relativePath = base + "/" + baseFileName(uploadFile);
            File dest = new File(basePath + relativePath);
            dest = FileUtil.touch(dest);
            FileUtil.move(src, dest, true);
            Files files = new Files().setCreated(date)
                    .setType(uploadFile.getContentType())
                    .setAbsolute(0)
                    .setDescription(StrKit.isBlank(description) ? relativePath : description)
                    .setUpdated(date)
                    .setPath(relativePath);
            files = Files.saveFiles(files);
            filesList.add(files);
        }
        renderJsonSuccess(filesList);
    }

    private String baseFileName(UploadFile uploadFile) {
        String suffix = uploadFile.getFileName();
        if (suffix.lastIndexOf(".") == -1) suffix = "";
        else suffix = suffix.substring(suffix.lastIndexOf("."));
        return String.valueOf(System.currentTimeMillis() + String.format("%.0f", Math.random() * 100000000) + suffix);
    }

    /**
     * 加载APP配置信息给前台
     */
    public void appInfo() {

    }

}
